<?php
/*
 * @Author: CHINAKAIYUAN<sunkaiyuan@namenode.cn>
 * @Date: 2022-02-05 12:05:33
 * @LastEditTime: 2023-10-20 10:49:26
 * @LastEditors: 孙开源 && sunkaiyuan@namenode.cn
 * @Description: 
 */

namespace App\Http\Services\Storage;

use App\Http\Services\Service;
use App\Repositories\AttachmentRepository;
use App\Repositories\MpcDeptAllocationRepository;
use App\Repositories\MpcDeptAllocationDetailRepository;

use Illuminate\Support\Facades\DB;

/**
 * @property MpcDeptAllocationRepository $repository
 * @property MpcDeptAllocationDetailRepository $Detail
 * @property AttachmentRepository $att
 */
class DeptAllocationService extends Service
    {

    public function boot(MpcDeptAllocationRepository $Repository, MpcDeptAllocationDetailRepository $detail, AttachmentRepository $att)
        {
        $this->repository = $Repository;
        $this->Detail     = $detail;
        $this->att        = $att;
        }
    public function list()
        {
        $data = $this->repository->condition(request())->getGrid();
        return $data;
        }
    public function info($requset)
        {
        return $this->repository->condition($requset)->getOne();
        }

    public function details()
        {
        return $this->Detail->condition(request())->getGrid();
        }
    protected function save($request)
        {
        $ReqData = $request->toArray();
        // DB::enableQueryLog();
        // dd(DB::getQueryLog());

        $data = $this->repository->whereId($request->input("id"))->first();
        if ($data && $data->status_id > 0) {
            fail("已审核单据禁止编辑！");
            }

        $ReqData['quantity'] =
            $ReqData['auxiliary_quantity'] = 0;
        $oldlocation_dept    = 0;
        $ReqData['details']  = collect($ReqData['details'])->map(function ($row) use (&$ReqData, &$oldlocation_dept)
            {
            if ($oldlocation_dept == 0) {
                $oldlocation_dept = $row['oldlocation']['department_id'];
                }
            else if ($oldlocation_dept != $row['oldlocation']['department_id']) {
                fail("同一个调拨单的原库位必须一致！保存失败");
                }
            if (is_numeric($row['id']) && $row['oldlocation']['department_id'] != auth()->user()->department_id) {
                fail("单据只能由【{$row['oldlocation']['department']['name']}】操作！");
                }
            $ReqData['quantity'] += $row['quantity'];
            $ReqData['auxiliary_quantity'] += $row['auxiliary_quantity'];
            return $row;
            });
        $ReqData['car_id']   = ($ReqData['car_id'] ?? "") == "" ? 0 : $ReqData['car_id'];
        $ReqData['carry_id'] = ($ReqData['carry_id'] ?? "") == "" ? 0 : $ReqData['carry_id'];
        $allot_data          = $this->repository->autosave($ReqData);

        $this->saveCar($allot_data);
        $this->saveCarry($allot_data);
        return $allot_data;
        }
    private function saveCarry($allot_data)
        {
        $allot_data->details->filter(function ($row) use ($allot_data)
            {
            if ($allot_data->carry_id == $row->carry_id)
                return;
            else if ($row->carry_id > 0)
                $row->removeCarryItem();

            if ($allot_data->carry_id > 0)
                $row->addCarryItem($allot_data->carry_id, $row->main->code);

            });
        }
    private function saveCar($allot_data)
        {
        $allot_data->details->filter(function ($row) use ($allot_data)
            {
            if ($allot_data->car_id == $row->car_id)
                return;
            else if ($row->car_id > 0)
                $row->removeCarItem();

            if ($allot_data->car_id > 0)
                $row->addCarItem($row->oldlocation->name, $row->location->name, $allot_data->car_id, $row->main->code);
            });
        }
    protected function audit($ids = null)
        {
        return $this->repository
            ->whereIn("id", $ids ?? $this->getRequestIds())->with(['details'])
            ->get()
            ->filter(function ($v)
                {
                if ($v->status_id != 0)
                    fail("单据:[{$v->code}]已审核！");
                auditSave($v);
                $v->details->filter(
                    function ($deltail) use ($v)
                        {
                        if ($deltail->oldlocation->department_id != auth()->user()->department_id) {
                            fail("单据:[{$v->code}]只能由【{$deltail->oldlocation->department->name}】操作！");
                            }
                        $deltail->addStorage("调拨入库", $v->code);
                        $deltail->mergeWhere(['location_id' => ['key' => 'oldlocation_id']])
                            ->useStorage("调拨出库", $v->code, $deltail->quantity, $deltail->auxiliary_quantity, "old_mpc_detail");
                        $deltail->subStorage("old_mpc_detail");
                        }
                );
                });
        }
    protected function noaudit($ids = null)
        {
        return $this->repository
            ->whereIn("id", $ids ?? $this->getRequestIds())->with(['details'])
            ->get()
            ->filter(function ($v)
                {
                if ($v->status_id != 1)
                    fail("单据:[{$v->code}]未审核！");

                auditSave($v, false);
                $v->details->filter(
                    function ($deltail) use ($v)
                        {
                        if ($deltail->oldlocation->department_id != auth()->user()->department_id) {
                            fail("单据:[{$v->code}]只能由【{$deltail->oldlocation->department->name}】操作！");
                            }
                        $deltail->noaddStorage();
                        $deltail->nosubStorage("old_mpc_detail");
                        $deltail->nouseStorage("old_mpc_detail");
                        }
                );

                $v->save();
                });
        }
    protected function auditItem()
        {
        $ids = $this->Detail->whereIn("id", $this->getRequestIds())->pluck("main_id");
        return $this->audit($ids);
        }
    protected function noauditItem()
        {
        $ids = $this->Detail->whereIn("id", $this->getRequestIds())->pluck("main_id");
        return $this->noaudit($ids);
        }
    protected function deleteItem()
        {
        $ids = $this->Detail->whereIn("id", $this->getRequestIds())->pluck("main_id");
        return $this->delete($ids);
        }
    protected function delete($ids = null)
        {
        return $this->repository
            ->whereIn("id", $ids ?? $this->getRequestIds())->with(['details'])
            ->autodelete()->filter(function ($row)
                {
                if ($row->status_id == 1)
                    fail("单据[{$row->code}]已审核！");
                return true;
                });
        }
    }